package se480.tracker;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import se480.tracker.client.QueryClient;
import se480.tracker.client.UpdateClient;
import se480.tracker.processor.Processor;
import se480.tracker.proxy.AsynchProxy;
import se480.tracker.proxy.SynchProxy;
import se480.tracker.service.RegistrationService;
import se480.tracker.tracker.Location;
import se480.tracker.tracker.Tracker;
import se480.tracker.tracker.TrackerA;
import se480.tracker.tracker.TrackerB;

/**
 * Main simulation controller
 * 
 * 
 * @author mmichalak
 *
 */
public class SimulationMain {
	static Logger logger = Logger.getLogger(SimulationMain.class.getName());
	
	EventProxy eventProxy = null;
	Processor proc1 = null;
	Processor proc2 = null;
	RegistrationService regSvc = null;
	AsynchProxy asynchProxy = null;
	SynchProxy synchProxy = null;
	
	public static void main(String[] args) {
		SimulationMain trackSim = new SimulationMain();
		trackSim.setupSimulation();
		// This starts the simulation
		trackSim.runSimulation();
		logger.debug("Ending Simulation...");
	}
	
	
	/**
	 * Create all the system objects and set relationships
	 */
	public void setupSimulation() {
		// This is the simulation driver based on the Event file
		eventProxy = new EventProxy();
		//evPrx.setQueryClientPrx( new QueryClient() );
		UpdateClient upClient = new UpdateClient();
		eventProxy.setUpdateClient(upClient) ;
		QueryClient queryClient = new QueryClient();
		eventProxy.setQueryClient(queryClient);

		// create datastore
		Map<String, ArrayList<Location>> dataStore = new HashMap<String, ArrayList<Location>>();
		
		// Setup initial Primary Processor
		proc1 = new Processor("P1");
		proc1.setDataStore(dataStore);  // Set DS for the processor
		Tracker p1TrackA = new TrackerA();
		proc1.setTrackerA(p1TrackA);
		Tracker p1TrackB = new TrackerB();
		proc1.setTrackerB(p1TrackB);
		
		// Setup initial Backup Processor
		proc2 = new Processor("P2");
		proc2.setDataStore(dataStore);  // Set DS for the processor
		Tracker p2TrackA = new TrackerA();
		proc2.setTrackerA(p2TrackA);
		Tracker p2TrackB = new TrackerB();
		proc2.setTrackerB(p2TrackB);
		
		// This provides registration and health services
		regSvc = new RegistrationService();
		regSvc.setPrimaryProc(proc1);
		regSvc.setBackupProc(proc2);
		eventProxy.setRegSvc(regSvc);
		
		asynchProxy = new AsynchProxy();
		asynchProxy.setRegSvc(regSvc);
		synchProxy = new SynchProxy();
		synchProxy.setRegSvc(regSvc);
		
		upClient.setProxy(asynchProxy);
		queryClient.setProxy(synchProxy);
		
	}
	
	public void runSimulation() {
		eventProxy.readEvents();
	}
}
